#!/usr/bin/env python
# -*- coding:utf-8 -*-

# file:course_dao.py
# author:张世航
# datetime:2024/12/20 23:50
# software: PyCharm
"""
this is function  description 
"""
# import module your need



# dao/course_dao.py
import pymysql
from config.config import DATABASE_CONFIG
from models.course import Course

def connect_db():
    """连接数据库"""
    try:
        connection = pymysql.connect(**DATABASE_CONFIG)
        return connection
    except pymysql.MySQLError as e:
        print(f"Error connecting to database: {e}")
        return None

def add_course(course):
    """添加课程信息"""
    connection = connect_db()
    if connection:
        try:
            with connection.cursor() as cursor:
                sql = "INSERT INTO course (Cno, Cname, Chours, Credit, Tno, StudentCount) VALUES (%s, %s, %s, %s, %s, %s)"
                cursor.execute(sql, (course.Cno, course.Cname, course.Chours, course.Credit, course.Tno, course.StudentCount))
                connection.commit()
                print("Course added successfully.")
        except pymysql.MySQLError as e:
            connection.rollback()
            print(f"Error adding course: {e}")
        finally:
            connection.close()

def delete_course(Cno):
    """根据课程编号删除信息"""
    connection = connect_db()
    if connection:
        try:
            with connection.cursor() as cursor:
                sql = "DELETE FROM course WHERE Cno = %s"
                cursor.execute(sql, (Cno,))
                connection.commit()
                print("Course deleted successfully.")
        except pymysql.MySQLError as e:
            connection.rollback()
            print(f"Error deleting course: {e}")
        finally:
            connection.close()

def query_course_by_name(name):
    """根据课程名称查询信息"""
    connection = connect_db()
    if connection:
        try:
            with connection.cursor() as cursor:
                sql = "SELECT * FROM course WHERE Cname = %s"
                cursor.execute(sql, (name,))
                results = cursor.fetchall()
                for row in results:
                    print(row)
        except pymysql.MySQLError as e:
            print(f"Error querying course: {e}")
        finally:
            connection.close()